package com.yuanfud.zuulServer.controller;

import com.yuanfud.common.exception.RestException;
import com.yuanfud.common.util.ErrorCode;
import com.yuanfud.common.util.JwtHandler;
import com.yuanfud.common.util.ResultBody;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.jose4j.lang.JoseException;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JWTValidateController {
    @RequestMapping(value="/validate/token",method = RequestMethod.GET,produces = "application/json")
    public ResultBody<Boolean> validateToken(@RequestHeader("Authorization") String token, @RequestHeader("loginId") String loginId) throws RestException {
        ResultBody<Boolean> resultBody=new ResultBody<Boolean>();
        System.out.println(token);
        System.out.println(loginId);
        if(token==null||loginId==null){
            throw new RestException(ErrorCode.REQUEST_PARAM_NULL_ERROR, ErrorCode.REQUEST_PARAM_NULL_ERROR_MSG);
        }
        try {
            JwtHandler.volatileToken(token,loginId);
            resultBody.setCode(ErrorCode.SUCCESS_OK);
            resultBody.setMsg(ErrorCode.SUCCESS_OK_MSG);
            resultBody.setData(true);

        } catch (InvalidJwtException e) {
            if (e.getMessage().equals("expiredJwt")) {
                throw new RestException(ErrorCode.ZUUL_TOKEN_VALIDATE_TIMEOUT_ERROR, ErrorCode.ZUUL_TOKEN_VALIDATE_TIMEOUT_ERROR_MSG);
            }
            else
                throw new RestException(ErrorCode.ZUUL_TOKEN_VALIDATE_NULL_ERROR, ErrorCode.ZUUL_TOKEN_VALIDATE_NULL_ERROR_MSG);
        }
        catch (JoseException e) {
            throw new RestException(ErrorCode.ZUUL_TOKEN_VALIDATE_NULL_ERROR,ErrorCode.ZUUL_TOKEN_VALIDATE_NULL_ERROR_MSG);
        }

        return resultBody;
    }
}
